/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.view;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ElementScatter;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;

import com.xuexiang.xui_lib.popup.ListConntainerDropdown;
import com.xuexiang.xui_lib.util.LogUtils;
import com.xuexiang.xui_lib.util.UntilTNT;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.provider.SetterProvider;
import com.xuexiang.xuidemo.util.AttrValue;
import com.xuexiang.xuidemo.util.ToastUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 下拉框统一样式组件
 *
 * @since 2021-03-30
 */
public class Dropdowntextview extends DirectionalLayout implements ListConntainerDropdown {
    private int listCnerhigde = LayoutConfig.MATCH_CONTENT;
    private boolean isClick = true; // 是否可以点击

    private Component modeComponent;
    private Component component;
    private Context context;
    private DependentLayout detlayout;
    private boolean isDix = true; // 判断图片的指向方向
    private boolean isText;
    private ListContainer listContainer;
    private PopupDialog popupDialog;
    private Text textbx;
    private TextField fieldtext;
    private Image imgbx;
    private AnimatorValue animator;
    private String[] data = null;
    private List<UntilTNT> list;
    private SetterProvider setterProvider;
    private boolean isAnimation; // 是否开启动画,默认为flea
    private ListContainerview listContainerview = null;
    private int withlenth;
    private static final int anInt100 = 100;
    private static final int anInt1000 = 1000;

    /**
     * 构造方法
     *
     * @param context 上下文
     */
    public Dropdowntextview(Context context) {
        super(context);
        this.context = context;
        initview();
        animatorValue();
    }

    /**
     * 构造方法
     *
     * @param context 上下文
     * @param attrSet 样式
     */
    public Dropdowntextview(Context context, AttrSet attrSet) {
        super(context, attrSet);
        this.context = context;
        isText = AttrValue.get(attrSet, "istext", true);
        isAnimation = AttrValue.get(attrSet, "isAnimation", false);
        initview();
        animatorValue();
    }

    /**
     * 构造方法
     *
     * @param context 上下文
     * @param attrSet 上下文
     * @param styleName 名字
     */
    public Dropdowntextview(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        this.context = context;
        initview();
        animatorValue();
    }

    /**
     * 设置内容
     *
     * @param dt 组件显示的内容
     */
    public void setStringArray(String[] dt) {
        this.data = Arrays.copyOf(dt,dt.length);
    }

    private void initview() {
        Component ct = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dropdown_textlayout, this, true);
        detlayout = (DependentLayout) ct.findComponentById(ResourceTable.Id_Detlayout);
        this.modeComponent = detlayout;
        textbx = (Text) ct.findComponentById(ResourceTable.Id_text_bx);
        fieldtext = (TextField) ct.findComponentById(ResourceTable.Id_field_text);
        imgbx = (Image) ct.findComponentById(ResourceTable.Id_img_bx);

        detlayout.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component ct) {
                modeComponent();
            }
        });
    }

    public void setPosition(Component ct) {
        this.modeComponent = ct;
    }

    private void modeComponent() {
        if (isClick) {
            if (data.length > 1) { // 当下拉的长度大于1的时候才会有下拉

                initdialog();
            } else {
                ToastUtil.showToast(getContext(), "没有更多的选项!");
            }
        }
    }

    private void initdialog() {
        if (isDix) { // 判断箭头的方向
            isDix = false;
            popupDialog = new PopupDialog(context, modeComponent);
            if (isAnimation) {
                animator.start();
            }
            popupDialog.setAutoClosable(true);
            popupDialog.setCustomComponent(initComponent());
            popupDialog.setMode(LayoutAlignment.BOTTOM);
            imgbx.setPixelMap(ResourceTable.Media_icon_sjt); // 向上的箭头
            popupDialog.setDialogListener(new BaseDialog.DialogListener() {
                @Override
                public boolean isTouchOutside() { // 监听点击外部时消失的dialog
                    isDix = true;
                    imgbx.setPixelMap(ResourceTable.Media_icon_xjt); // 箭头向下
                    return false;
                }
            });
            popupDialog.show();
        } else {
            isDix = true;
            imgbx.setPixelMap(ResourceTable.Media_icon_xjt);
        }
    }

    /**
     * 此方法不对外
     *
     * @return 返回一个控件
     */
    public Component initComponent() {
        Component ct = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_listtainer_onetext_layout,
            null, false);
        listContainer = (ListContainer) ct.findComponentById(ResourceTable.Id_listconid);
        listContainer.enableScrollBar(ct.AXIS_Y, true); // 沿着Y轴,启动滚动条
        listContainer.setHeight(listCnerhigde);

        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listcontainer, Component ct, int i, long l) {
                UntilTNT untile = (UntilTNT) listcontainer.getItemProvider().getItem(i);
                if (isText) {
                    textbx.setText(untile.getName());
                    if (listContainerview != null) {
                        listContainerview.onItemClickedtext(untile.getName());
                    }
                } else {
                    fieldtext.setText(untile.getName());
                }
                isDix = true;
                imgbx.setPixelMap(ResourceTable.Media_icon_xjt);
                popupDialog.hide();
            }
        });
        list = new ArrayList<>();
        for (int i = 0; i < data.length; i++) {
            UntilTNT untile = new UntilTNT();
            untile.setDisplay(false);
            untile.setName(data[i]);
            list.add(untile);
        }
        setterProvider = new SetterProvider(list, context);
        listContainer.setItemProvider(setterProvider);
        this.component = ct;
        return ct;
    }

    /**
     * 设置 listCnerhigde
     *
     * @param listhigde 长度
     */
    public void setlistCnerhigde(int listhigde) {
        this.listCnerhigde = listhigde;
    }

    /**
     * 得到类型
     *
     * @return 返回isclick
     */
    public boolean getisClick() {
        return this.isClick;
    }

    /**
     * 定义外部的接口
     *
     * @since 2021-03-30
     */
    public interface ListContainerview {
        /**
         * 内部方法
         *
         * @param data 得到的数据
         */
        void onItemClickedtext(String data);
    }

    public void setListview(ListContainerview containerview) {
        this.listContainerview = containerview;
    }

    /**
     * 设置整个背景的背景颜色
     *
     * @param element
     */
    public void setbackgroud(Element element) {
        detlayout.setBackground(element);
    }

    /**
     * 设置是否可以点击状态切换
     *
     * @param isCk ture 可以点击
     */
    public void setnocilik(boolean isCk) {
        this.isClick = isCk;
        Element touchedBackGround;
        if (isClick) {
            touchedBackGround = ElementScatter.getInstance(context)
                .parse(ResourceTable.Graphic_background_ability_xtoast);
            fieldtext.setEnabled(true);
        } else {
            fieldtext.setEnabled(false);
            touchedBackGround = ElementScatter.getInstance(context)
                .parse(ResourceTable.Graphic_backgroud_xlknobj);
        }
        detlayout.setBackground(touchedBackGround);
    }

    /**
     * 设置是否显示编辑框
     */
    public void settextfile() {
        textbx.setVisibility(Component.HIDE); // text默认是显示的
        fieldtext.setVisibility(Component.VISIBLE);
        this.isText = false; // 默认是ture
    }

    /**
     * 如果设置输入框的宽度 需要先调用settextfile
     *
     * @param with 宽度
     */
    public void settexttypewith(int with) {
        withlenth = AttrHelper.vp2px(with, context);
        if (isText) {
            textbx.setWidth(withlenth);
        } else {
            fieldtext.setWidth(withlenth);
        }
    }

    /**
     * 文本框
     *
     * @param content 传入显示的内容
     */
    public void setTextContent(String content) {
        textbx.setText(content);
    }

    private void animatorValue() {
        animator = new AnimatorValue();
        animator.setDuration(anInt1000); // 设置动画的持续时间
        animator.setDelay(anInt100); // 设置动画延迟
        animator.setCurveType(Animator.CurveType.BOUNCE); // 设置动画师使用的曲线，默认情况下，该曲线是线性插值器

        animator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float value) {
                component.setContentPosition(0, anInt100 * value);
            }
        });
        animator.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator amtr) {
            }

            @Override
            public void onStop(Animator amtr) {
                component.setContentPosition(0, 0);
            }

            @Override
            public void onCancel(Animator amtr) {
            }

            @Override
            public void onEnd(Animator amtr) {
            }

            @Override
            public void onPause(Animator amtr) {
            }

            @Override
            public void onResume(Animator amtr) {
            }
        });
    }
}
